// Fill out your copyright notice in the Description page of Project Settings.


#include "PawnBase.h"

#include "FoodGeneratorBase.h"
#include "SnakeBase.h"

// Sets default values
APawnBase::APawnBase()
{
 	// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
}

// Called when the game starts or when spawned
void APawnBase::BeginPlay()
{
	Super::BeginPlay();
	
	CreateSnakeActor();
	CreateFoodGeneratorActor();
	RunSnake();
}

// Called every frame
void APawnBase::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

// Called to bind functionality to input
void APawnBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);
	
	PlayerInputComponent->BindAxis("Vertical", this, &APawnBase::HandlePlayerVerticalInput);
	PlayerInputComponent->BindAxis("Horizontal", this, &APawnBase::HandlePlayerHorizontalInput);
}

void APawnBase::CreateSnakeActor()
{
	SnakeActor = GetWorld()->SpawnActor<ASnakeBase>(SnakeActorClass, FTransform());
}

void APawnBase::CreateFoodGeneratorActor()
{
	FoodGeneratorActor = GetWorld()->SpawnActor<AFoodGeneratorBase>(FoodGeneratorClass, FTransform(FoodGeneratorPositionCell));
}

void APawnBase::HandlePlayerVerticalInput(float Value)
{
	if (IsValid(SnakeActor))
	{
		if (Value > 0 && SnakeActor->GetCurrentMovementDirection() != EMovementDirection::DOWN)
		{
			SnakeActor->SetMovementDirection(EMovementDirection::UP);
		}
		else if (Value < 0 && SnakeActor->GetCurrentMovementDirection() != EMovementDirection::UP)
		{
			SnakeActor->SetMovementDirection(EMovementDirection::DOWN);
		}
	}
}

void APawnBase::HandlePlayerHorizontalInput(float Value)
{
	if (IsValid(SnakeActor))
	{
		if (Value > 0 && SnakeActor->GetCurrentMovementDirection() != EMovementDirection::LEFT)
		{
			SnakeActor->SetMovementDirection(EMovementDirection::RIGHT);
		}
		else if (Value < 0 && SnakeActor->GetCurrentMovementDirection() != EMovementDirection::RIGHT)
		{
			SnakeActor->SetMovementDirection(EMovementDirection::LEFT);
		}
	}
}

void APawnBase::RunSnake()
{
	SnakeActor->CreateSnake();
	SnakeActor->Run();
	
	FoodGeneratorActor->SetSnakeActor(SnakeActor);
	FoodGeneratorActor->Run();
}

ASnakeBase* APawnBase::GetSnake()
{
	return SnakeActor;
}

AFoodGeneratorBase* APawnBase::GetFoodGenerator()
{
	return FoodGeneratorActor;
}



